package com.example.test.entity;



import java.util.Arrays;


public class Bank {

    private final double[] accounts;

    private final Object o = new Object();

    public Bank(int n,double initialBalance) {
        this.accounts = new double[n];
        Arrays.fill(accounts,initialBalance);
    }

    public synchronized void  transfer(int from , int to ,double amount) throws InterruptedException {
        synchronized (o){
            try {
                if (accounts[from]<amount) o.wait();
                System.out.println(Thread.currentThread());
                accounts[from] -= amount;
                System.out.printf("%10.2f from %d to %d",amount,from,to);
                accounts[to] += amount;
                System.out.printf(" Total Balance: %10.2f%n ",getTotalBalance());
            }finally {
                o.notify();
            }
        }
    }

    public synchronized double getTotalBalance(){
        double sum = 0;
        for (double a:accounts) {
            sum += a;
        }
        return sum;
    }


    public int size(){
        return accounts.length;
    }

}
